﻿using Clancy.Interfaces;
using ReactiveUI;
using System;
using System.ComponentModel;
using System.Reactive.Linq;

namespace Clancy.Ui.ViewModels
{
    public class PropertyEditorViewModel : ClancyEditorViewModelBase
    {
        private readonly ISelectionManager m_SelectionManager;
        private ObservableAsPropertyHelper<ISelectable> m_CurrentSelectionPropertyHelper;
        private IDisposable m_SurveilanceSettingsObservalbe;

        public PropertyEditorViewModel(IOperationalAdapterProvider operationalAdapterProvider, ISelectionManager selectionManager, ISurveilanceStorage surveilanceStorage)
            : base(operationalAdapterProvider, surveilanceStorage)
        {
            m_SelectionManager = selectionManager;

            InitSelectionModeProperties();
        }

        public ISelectable CurrentSelection
        {
            get
            {
                if (m_CurrentSelectionPropertyHelper == null)
                    return null;
                return m_CurrentSelectionPropertyHelper.Value;
            }
        }

        private void AttachSelectedSurveilanceOnlineUpdate(ISurveilanceObject surveilanceObject)
        {
            if (m_SurveilanceSettingsObservalbe != null)
                m_SurveilanceSettingsObservalbe.Dispose();

            if (surveilanceObject == null)
                return;

            m_SurveilanceSettingsObservalbe = Observable.FromEventPattern<PropertyChangedEventArgs>(surveilanceObject, "PropertyChanged").Subscribe(async pattern =>
            {
                await OperationAdapter.UpdateSurveilanceObject(surveilanceObject, pattern.EventArgs.PropertyName);
            });
        }

        private void InitSelectionModeProperties()
        {
            m_CurrentSelectionPropertyHelper = new ObservableAsPropertyHelper<ISelectable>(m_SelectionManager.CurrentSelection,
                _ =>
                {
                    this.RaisePropertyChanged("CurrentSelection");
                    if (CurrentSelection is ISurveilanceObject)
                    {
                        AttachSelectedSurveilanceOnlineUpdate(CurrentSelection as ISurveilanceObject);
                    }
                });
            DisposableRxElements.Add(m_CurrentSelectionPropertyHelper);
        }
    }
}